<script setup>
import { EmailOutlined, LockOpenOutlined } from "@vicons/material";
import { noteBaseRequest } from "@/request/noterequset";
import { useMessage, useLoadingBar } from "naive-ui";
import { useLoginModalStore } from "@/stores/loginModalStore";
import {useUserStore} from "@/stores/userStore"
import { ref } from "vue";


const message = useMessage();
const loadingBar = useLoadingBar();
//自定义事件
const emits = defineEmits(["changeStep"]);

const loginModelStore = useLoginModalStore();
const { changeLoginModalShowStatus } = loginModelStore;

const userStore = useUserStore();
const {userInfo,setUserInfo} = userStore;
//登录表单值
const loginFormValue = ref({
  email: "",
  password: "",
  trim: false,
});
//登录表单验证规则
const loginFormRules = {
  email: [
    {
      required: true,
      message: "请输入邮箱号",
      trigger: ["input", "blur"],
    },
    {
      message: "请正确输入邮箱号",
      trigger: ["input", "blur"],
      validator: (rule, value) => {
        return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value);
      },
    },
  ],
  //blur失去焦点
  password: {
    required: true,
    message: "请输入密码",
    trigger: ["input", "blur"],
  },
  trim: {
    message: "请认真阅读app条款与协议",
    trigger: "change",
    validator: (rule, value) => {
      return value;
    },
  },
};
//登录表单引用对象
const loginFormRef = ref(null);

const loadingBtn = ref(false);
//去登陆
const toLogin = (e) => {
  e.preventDefault();
  loginFormRef.value?.validate(async (errors) => {
    if (!errors) {
      //发送登录请求
      loadingBar.start();
      loadingBtn.value = true;
      const { data: responseData } = await noteBaseRequest
        .post("/user/login/email/password", {
          email: loginFormValue.value.email,
          password: loginFormValue.value.password,
        })
        .catch(() => {
          //发送404，500，400.....
          message.error("发送登录请求失败");
          loadingBar.error();

          setTimeout(() => {
            loadingBtn.value = false;
          }, 1500);
          throw "发送登录请求失败";
        });
      //得到服务器返回数据进行处理
      console.log(responseData);
      if (responseData.success) {
        loadingBar.finish();
        message.success(responseData.message);
        changeLoginModalShowStatus(false);
        localStorage.setItem('userToken',responseData.data.userToken)
        setUserInfo(responseData.data.user)
      } else {
        loadingBar.error();
        message.error(responseData.message);
      }

      setTimeout(() => {
        loadingBtn.value = false;
      }, 1500);
    }
  });
};
</script>

<template>
  <n-card>
    <!--          前往注册-->
    <n-space justify="space-between" align="center">
      <h2>登录</h2>
      <n-text depth="3">
        暂无账号？
        <n-button text="true" type="info" @click="emits('changeStep', 2)">
          前往注册
        </n-button>
      </n-text>
    </n-space>
    <!--           登录表单-->
    <n-form :model="loginFormValue" :rules="loginFormRules" ref="loginFormRef">
      <!--          path明确验证规则 first只显示第一个错误-->
      <n-form-item label="邮箱号码" path="email" first>
        <n-input
          placeholder="请输入邮箱号码！"
          v-model:value="loginFormValue.email"
        >
          <template #prefix>
            <n-icon :component="EmailOutlined" />
          </template>
        </n-input>
      </n-form-item>
      <n-form-item label="密码" path="password">
        <n-input
          placeholder="请输入密码！"
          type="password"
          v-model:value="loginFormValue.password"
        >
          <template #prefix>
            <n-icon :component="LockOpenOutlined" />
          </template>
        </n-input>
      </n-form-item>
      <n-form-item :show-label="false" path="trim">
        <n-checkbox v-model:checked="loginFormValue.trim"
          >是否同意该
        </n-checkbox>
        <n-button text type="info"> 《条款与协议》 </n-button>
      </n-form-item>
      <n-form-item :show-label="false">
        <n-button :disabled="loadingBtn" block type="success" @click="toLogin">
          登录
        </n-button>
      </n-form-item>
    </n-form>
    <!--          忘记密码-->
    <n-space justify="center" style="cursor: pointer">
      <n-text depth="3">忘记密码？</n-text>
    </n-space>
  </n-card>
</template>
